<template>
  <a-skeleton :loading="loading" active :title="false" :paragraph="{ rows: 6, width: '100%' }">
    <a-card hoverable :bordered="false" size="small">
      <a-table
        size="small"
        :dataSource="dataSource"
        :columns="columns"
        :pagination="false"
        :scroll="{ x: 800 }"
      >
        <template #headerCell="{ column }">
          <template v-if="column.key === 'operation'">
            <div style="display: flex; justify-content: space-between; align-items: center">
              <span> 操作 </span>
              <a-button type="primary" size="middle" @click="addJob" v-auth="['admin', 'job:add']">
                新增
              </a-button>
            </div>
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'enabled'">
            <span>
              <a-switch
                v-model:checked="record.enabled"
                @change="changeEnabled(record, record.enabled)"
              />
            </span>
          </template>
          <template v-if="column.key === 'operation'">
            <span>
              <a-button
                type="link"
                size="middle"
                @click="editJob(record)"
                v-auth="['admin', 'job:edit']"
                >编辑</a-button
              >
              <a-divider type="vertical" />
              <a-popconfirm
                v-if="dataSource.length"
                title="确定删除本条数据吗?"
                @confirm="onDelete(record.id)"
              >
                <a-button type="link" size="middle" v-auth="['admin', 'job:del']">删除</a-button>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>
      <!--分页组件-->
      <a-pagination
        style="margin-top: 10px"
        size="small"
        v-model:current="page"
        :total="total"
        show-size-changer
        show-quick-jumper
        :show-total="(total) => `共有 ${total} 条数据`"
        @showSizeChange="onShowSizeChange"
        @change="pageChange"
      />

      <JobModal ref="jobModalRef" />
    </a-card>
  </a-skeleton>
</template>
<script lang="ts">
  import { defineComponent, ref, onMounted, watch, createVNode } from 'vue';
  import { Modal, notification } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import JobModal from './jobModal.vue';
  import { getJobsApi, delJobApi, editJobApi } from '/@/api/job';
  import { reload } from './index';

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '排序',
      dataIndex: 'jobSort',
      key: 'jobSort',
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
    },
    {
      title: '创建日期',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 160,
    },
  ];

  export default defineComponent({
    components: { JobModal },
    setup() {
      const loading = ref<boolean>(true);
      const dataSource = ref<any>([]);
      const total = ref<number>(0);
      const page = ref<number>(1);
      const pageSize = ref<number>(10);

      const pageChange = (current: number) => {
        page.value = current;
      };

      const onShowSizeChange = (_current: number, size: number) => {
        page.value = 1;
        pageSize.value = size;
      };

      const loadJobs = async (params: object) => {
        try {
          let res = await getJobsApi({
            ...params,
            page: page.value - 1,
            size: pageSize.value,
            sort: ['jobSort,asc', 'id,desc'],
          });
          dataSource.value = res?.content;
          total.value = res?.totalElements;
        } catch (error) {}
      };

      watch([page, pageSize, reload], () => {
        const params = {};
        loadJobs(params);
      });

      onMounted(() => {
        setTimeout(async () => {
          loading.value = false;
        }, 300);
        loadJobs({});
      });

      const jobModalRef = ref();
      const addJob = () => {
        jobModalRef.value.open(true, {});
      };
      const editJob = (record) => {
        jobModalRef.value.open(false, { ...record });
      };

      const changeEnabled = (data, val) => {
        Modal.confirm({
          title: '提示',
          icon: createVNode(ExclamationCircleOutlined),
          content: '此操作将' + (val ? '启用' : '禁用') + data.name + ', 是否继续？',
          async onOk() {
            try {
              await editJobApi(data);
              notification['success']({
                message: '操作成功!',
                duration: 3,
              });
            } catch (error) {
              data.enabled = !data.enabled;
            }
          },
          onCancel() {
            data.enabled = !data.enabled;
          },
        });
      };

      const onDelete = async (id) => {
        try {
          const ids = [id];
          await delJobApi(ids);

          if (dataSource.value.length == ids.length && page.value > 0) {
            --page.value;
          } else {
            reload.value = !reload.value;
          }

          notification['success']({
            message: '删除成功!',
            duration: 3,
          });
        } catch (error) {}
      };

      return {
        loading,
        page,
        total,
        dataSource,
        pageChange,
        onShowSizeChange,
        columns,
        addJob,
        editJob,
        changeEnabled,
        onDelete,
        jobModalRef,
      };
    },
  });
</script>
